package com.beiding.my.bemapping;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class BeTypeMapper<T> {

    BeTypeMapper() {
    }


    //支持复杂条件的解析

    //映射的实际类型
    Class<T> type;

    //名称
    String name;

    //field
    private String id = Id.type();

    //映射的表名
    String tableName;

    //所有映射的字段
    private List<BeFieldMapper> fields = new ArrayList<>();

    private Map<String, BeFieldMapper> nameBeFieldMapperMap = new HashMap<>();

    private Map<String, BeFieldMapper> idBeFieldMapperMap = new HashMap<>();

    void addField(BeFieldMapper field) {
        this.fields.add(field);
        nameBeFieldMapperMap.put(field.getName(), field);
        idBeFieldMapperMap.put(field.getId(), field);
    }

    //根据名称获取字段
    public BeFieldMapper getFieldByName(String field) {
        return nameBeFieldMapperMap.get(field);
    }

    public BeFieldMapper getFieldById(String field) {
        return idBeFieldMapperMap.get(field);
    }

    public String getTableName() {
        return tableName;
    }

    public String getName() {
        return name;
    }

    public String getId() {
        return id;
    }

    public Class getType() {
        return type;
    }

    public List<BeFieldMapper> getFields() {
        return fields;
    }

    public T newBeByFieldName(Map<String, Object> values) {
        return newBe(values, nameBeFieldMapperMap);
    }

    private T newBe(Map<String, Object> values, Map<String, BeFieldMapper> nameBeFieldMapperMap) {
        T be = newBe();
        values.forEach((k, v) -> {
            BeFieldMapper beFieldMapper = nameBeFieldMapperMap.get(k);
            if (beFieldMapper != null) {
                beFieldMapper.set(be, v);
            }
        });
        return (T) be;
    }

    public T newBeByFieldId(Map<String, Object> values) {
        return newBe(values, idBeFieldMapperMap);
    }

    public void assignmentByFieldName(T be, Map<String, Object> values) {
        values.forEach((k, v) -> {
            assignmentByFieldName(be, k, v);
        });
    }

    public void assignmentByFieldId(T be, Map<String, Object> values) {
        values.forEach((k, v) -> {
            assignmentByFieldId(be, k, v);
        });
    }

    public void assignmentByFieldName(T be, String field, Object value) {
        BeFieldMapper beFieldMapper = nameBeFieldMapperMap.get(field);
        if (beFieldMapper != null) {
            beFieldMapper.set(be, value);
        }
    }

    public void assignmentByFieldId(T be, String fieldId, Object value) {
        BeFieldMapper beFieldMapper = idBeFieldMapperMap.get(fieldId);
        if (beFieldMapper != null) {
            beFieldMapper.set(be, value);
        }
    }

    public T newBe() {
        try {
            return type.newInstance();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }


}
